from django.shortcuts import render, redirect, HttpResponse
from web.Forms import account
from django.http import JsonResponse
from web.Forms.account import LoginForm
from web import models
from utils.image_code import check_code
from io import BytesIO
from django.db.models import Q
import re


# 发送短信
def send_sms(request):
    # print(request.GET)
    # 发送短信之前进行校验，重新定义一个form组件
    form = account.SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 注册
def Register(request):
    if request.method == 'GET':
        form = account.RegisterModelForm()
        return render(request, 'register.html', locals())
    # 如果是post请求的话，进行一个相应的处理（检验）
    form = account.RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 注意 密码是明文进入数据库 后期需要手动MD5加密 instance= form.save()
        # instance 这个是生成的数据 form.instance.password
        form.save()
        return JsonResponse({'status': True, 'data': '/web/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 短信登录
def Login(request):
    if request.method == 'GET':
        # 进行渲染
        form = LoginForm()
        return render(request, 'login.html', locals())
    # 进行校验
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data['telephone']
        user_obj = models.UserIfo.objects.filter(telephone=telephone).first()
        # 登录成功以后将进行username id 放到session表中
        request.session['user_id'] = user_obj.id
        request.session['user_name'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/web/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 多方式验证码登录
def LoginCode(request):
    if request.method == 'GET':
        # 渲染
        form = account.LoginCodeForm(request)
        return render(request, 'login_code.html', locals())
    form = account.LoginCodeForm(request, request.POST)
    if form.is_valid():
        # 校验账号密码是否正确
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        # 多方式登录(也可以用re进行检验username是什么 ) Q 联合查询，F 取值
        user_obj = models.UserIfo.objects.filter(
            Q(username=username) | Q(telephone=username) | Q(email=username)).filter(
            password=password
        ).first()

        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session['user_name'] = user_obj.username
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
    return render(request, 'login_code.html', locals())


# 验证码图片生成
def GetCode(request):
    image_object, code = check_code()
    # 存放验证码code
    request.session['img_code'] = code
    # 设置过期时间
    request.session.set_expiry(180)
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


# index
def index(request):
    return render(request, 'index.html')


# logout
def logout(request):
    request.session.flush()
    return redirect('index')
